package mqs

import (
	"context"
	"github.com/zeromicro/go-zero/core/jsonx"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	mqmodel "xialou_platform/app/rqueue/model"
	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/wallet/api/internal/svc"
	"xialou_platform/services/wallet/rpc/walletClient"
)

type XiaLouWalletIncomeExpire struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewXiaLouWalletIncomeExpire(ctx context.Context, svcCtx *svc.ServiceContext) *XiaLouWalletIncomeExpire {
	logx.Info("MQ: NewXiaLouWalletIncomeExpire- init")
	return &XiaLouWalletIncomeExpire{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *XiaLouWalletIncomeExpire) Consume(_, val string) error {
	logx.Infof("XiaLouWalletIncomeExpire->Consume :%v", val)
	var message mqmodel.XiaLouWalletIncomeModel
	if err := jsonx.Unmarshal([]byte(val), &message); err != nil {
		logx.WithContext(l.ctx).Error("XiaLouWalletIncomeExpire->Consume Unmarshal err : %v , val : %s", err, val)
		return err
	}

	//执行业务..
	if err := l.execService(message); err != nil {
		if err == sqlc.ErrNotFound {
			return nil
		}
		logx.WithContext(l.ctx).Errorf("XiaLouWalletIncomeExpire->execService  err : %v , val : %s , message:%+v", err, val, message)
		return err
	}

	return nil
}

// 处理收入分账
func (l *XiaLouWalletIncomeExpire) execService(message mqmodel.XiaLouWalletIncomeModel) error {
	// 该商家的销氪
	var AgentId int64
	store, err := l.svcCtx.AgentRpc.StoreById(l.ctx, &agentClient.IdBody{Id: message.StoreId})
	if store != nil {
		AgentId = store.AgentId
	}

	if message.Business == 1 {
		// 商家售卡，利润只给商家，如果是销氪卖平台的卡，才给销氪分账
		message.Profit = 0
		if message.StoreId == 1 && message.Referrer > 0 {

			agentInfo, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: message.Referrer})
			if err != nil {
				logx.Error("查询代理商信息失败", logx.Field("err", err))
				return err
			}

			income := int64(float64(message.Income) * agentInfo.CardRate / 100 * 0.9)
			logx.Info("商家入账：", income)
			if income > 0 {
				_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
					SourceType:  1,
					SourceId:    message.Referrer,
					Amount:      int64(float64(message.Income) * agentInfo.CardRate / 100 * 0.9),
					OrderId:     message.OrderId,
					Description: message.Description,
					Business:    message.Business,
				})
				if err != nil {
					logx.Error("商家入账失败", logx.Field("err", err))
					return err
				}
			}
		}
	}

	if message.StoreId > 1 {
		logx.Infof("商家入账：%d", message.StoreId)
		// 售会员卡扣5%手续费，团购、买单的手续费已经包含在服务费率中
		income := message.Income

		switch message.Business {
		case 1:
			income = int64(float64(message.Income) * 0.95)
		}

		if income > 0 {
			_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
				SourceType:  2,                   // 关联类型（1.代理商 2.商家）
				SourceId:    message.StoreId,     // 商家ID
				Amount:      income,              // 收入金额
				OrderId:     message.OrderId,     // 订单ID;
				Description: message.Description, // 订单备注
				Business:    message.Business,    // 业务类型: 业务（1.售卡 2.团购 3.买单）
			})
			if err != nil {
				logx.Info("商家入账失败", logx.Field("err", err))
				return err
			}
		}
	}

	// 团购和赚钱收益分账
	if message.Profit > 0 {
		var dividedProfit int64
		// 绑定用户的销氪分账
		if message.Referrer > 0 {

			dividedProfit, err = l.divideReferrerAccount(message.Referrer, message.Business, message.Profit, message.OrderId, message.Description)
			if err != nil {
				logx.WithContext(l.ctx).Errorf("绑定用户的销氪分账 err : %v , val : %s , message:%+v", err, message)
				return err
			}

		}

		// 绑定商家的销氪分账
		if AgentId > 0 {
			err = l.divideAccount(AgentId, message.Business, message.Profit, dividedProfit, message.OrderId, message.Description)
			if err != nil {
				logx.WithContext(l.ctx).Errorf("绑定商家的销氪分账 err : %v , val : %s , message:%+v", err, message)
				return err
			}
		}

	}

	return nil
}

// 绑定商家的销氪分账 (销氪id，业务，利润，已分出利润,订单号，描述) 返回（错误）
func (l *XiaLouWalletIncomeExpire) divideAccount(agentId, business, profit, dividedProfit, orderId int64, desc string) error {

	agentInfo, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: agentId})
	if err != nil {
		return err
	}

	// 销氪收益 = 利润 * 利润率 * 90%（扣除10%手续费）
	agentProfit := int64(float64(profit) * agentInfo.ProfitRate / 100 * 0.9)
	// 服务商销氪 = 利润 * 利润率 * 10%（由代理商利润出）* 90%（扣除10%手续费）
	serviceProfit := int64(float64(profit) * agentInfo.ProfitRate / 100 * 0.1 * 0.9)

	if agentProfit > 0 {
		_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
			SourceType:  1,
			SourceId:    agentId,
			Amount:      agentProfit,
			OrderId:     orderId,
			Description: desc,
			Business:    business,
		})
		if err != nil {
			return err
		}
	}

	if agentInfo.ParentUid > 0 {
		// 有父级销氪，但父级销氪不是代理商
		if agentInfo.ParentUid != agentInfo.TopUid {

			if serviceProfit > 0 {
				_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
					SourceType:  1,
					SourceId:    agentInfo.ParentUid,
					Amount:      serviceProfit,
					OrderId:     orderId,
					Description: desc,
					Business:    business,
				})
				if err != nil {
					return err
				}
			}
			if agentInfo.TopUid > 0 {
				topProfit := (profit - agentProfit - serviceProfit - dividedProfit) * 80 / 100 // 省级服务商10% + 平台手续费10%）
				if topProfit > 0 {
					_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
						SourceType:  1,
						SourceId:    agentInfo.TopUid,
						Amount:      topProfit,
						OrderId:     orderId,
						Description: desc,
						Business:    business,
					})
					if err != nil {
						return err
					}
				}

				// 省级运营中心 占10%

			}

		} else {
			// 既是父级销氪，又是代理商
			topProfit := (profit - agentProfit - dividedProfit) * 80 / 100 // 剩下的利润（省级服务商10% + 平台手续费10%）
			if topProfit > 0 {
				_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
					SourceType:  1,
					SourceId:    agentInfo.ParentUid,
					Amount:      topProfit,
					OrderId:     orderId,
					Description: desc,
					Business:    business,
				})
				if err != nil {
					return err
				}
			}

		}

	}

	return nil
}

// 绑定用户销氪分账(销氪id，业务，利润，订单号，描述) 返回（已分账利润，错误）
func (l *XiaLouWalletIncomeExpire) divideReferrerAccount(agentId, business, profit, orderId int64, desc string) (dividedProfit int64, err error) {

	agentInfo, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: agentId})
	if err != nil {
		return dividedProfit, err
	}
	// 销氪利润收益 = 利润 * 30% * 90%（扣除10%手续费）
	agentProfit := int64(float64(profit) * 0.3 * 0.9)
	if agentProfit > 0 {
		_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
			SourceType:  1,
			SourceId:    agentId,
			Amount:      agentProfit,
			OrderId:     orderId,
			Description: desc,
			Business:    business,
		})
		if err != nil {
			return dividedProfit, err
		}
		dividedProfit += agentProfit
	}

	// 有父级销氪，但父级销氪不是代理商
	if agentInfo.ParentUid > 0 && agentInfo.ParentUid != agentInfo.TopUid {
		// 服务商利润 = 销氪利润 * 10%（由代理商利润出）* 90%（扣除10%手续费）
		serviceProfit := int64(float64(profit) * 0.3 * 0.1 * 0.9)
		if serviceProfit > 0 {
			_, err = l.svcCtx.WalletRpc.WalletIncome(l.ctx, &walletClient.WalletIncomeReq{
				SourceType:  1,
				SourceId:    agentInfo.ParentUid,
				Amount:      serviceProfit,
				OrderId:     orderId,
				Description: desc,
				Business:    business,
			})
			if err != nil {
				return dividedProfit, err
			}
			dividedProfit += serviceProfit
		}

	}

	return dividedProfit, nil
}
